<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools>
        <!-- 左侧插槽 -->
        <template #slot-left>
          <span>共 {{ total }} 条记录</span>
        </template>
        <!-- 右侧插槽 -->
        <template #slot-right>
          <el-button type="danger" size="small" @click="$router.push('/excel')">导入excel</el-button>
          <el-button type="success" size="small" @click="downloadExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 表格 -->

      <el-card style="margin-top: 10px;">
        <el-table :data="employeesList" border>
          <el-table-column type="index" label="序号" />
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="staffPhoto" label="头像">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt=""> -->
              <image-holder :img="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column prop="mobile" label="手机号" />
          <el-table-column prop="workNumber" label="工号" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ scope.row.formOfEmployment|formatEmployment }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column sortable label="入职时间">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry|formatTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="assignRoles(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页区域 -->
          <el-pagination
            :current-page="query.page"
            :page-sizes="[10, 15, 20, 25]"
            :page-size="query.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
        <!-- 新增弹框 -->
        <el-dialog
          title="新增员工"
          :visible.sync="showDialog"
          @close="closeDialog"
        >
          <!-- form表单组件 -->
          <EmpDialog ref="addForm" @close="showDialog=false" @update="updateEmp" />
        </el-dialog>

        <!-- 分配角色弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="showRoleDialog"
        >
          <assign-role v-if="showRoleDialog" :employee-id="employeeId" @close="showRoleDialog=false" />
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import EmpDialog from './EmpDialog.vue'
import AssignRole from './assignRole.vue'
import dayjs from 'dayjs'
export default {
  name: 'Employees',
  components: {
    EmpDialog,
    AssignRole
  },
  filters: {
    formatEmployment(val) {
      // console.log(val)
      const obj = EmployeeEnum.hireType.find(item => item.id === Number(val))
      return obj ? obj.value : '未知'
    },
    formatTime(time) {
      // console.log(time)
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 10
      },
      total: 100,
      employeesList: [],
      showDialog: false,
      showRoleDialog: false,
      employeeId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    // 分配角色按钮
    assignRoles(id) {
      this.showRoleDialog = true
      this.employeeId = id
    },

    // 转换数据结构
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 英文key数组
      const headerArr = Object.keys(rows[0])
      const header = headerArr.map(item => {
        return map[item]
      })
      const data = rows.map(item => {
        return Object.values(item)
      })
      return { header, data }
    },

    // 导出excel
    async downloadExcel() {
      // 点击导出按钮 后获取最新的数据
      const res = await getEmployeesList()
      // 接收转换格式的数据
      const { header, data } = this.transData(res.data.rows)
      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 关闭弹框
    closeDialog() {
      // 调用组件重置表单方法
      this.$refs.addForm.resetForm()
    },

    // 添加成功
    updateEmp() {
      this.showDialog = false
      this.getEmployeesList()
    },

    // 删除员工信息
    async delEmployee(id) {
      // console.log(id)
      const confirmRes = await this.$confirm('此操作将永久删除该员工信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmRes)
      if (confirmRes === 'cancel') return
      const res = await delEmployee(id)
      // console.log(res)
      // 删除最后一页最后一条数据分页出现异常的问题
      if (this.employeesList.length === 1) {
        this.query.page--
        // 当是第一页最后一条数据时
        if (this.query.page < 1) {
          this.query.page = 1
        }
      }
      // 提示
      this.$message.success(res.message)
      // 更新视图
      this.getEmployeesList()
    },

    // 获取员工列表
    async getEmployeesList() {
      const res = await getEmployeesList(this.query)
      // console.log(res)
      this.employeesList = res.data.rows
      this.total = res.data.total
    },

    // 改变每页显示条数
    handleSizeChange(newSize) {
      this.query.size = newSize
      this.getEmployeesList()
    },

    // 改变当前页
    handleCurrentChange(newPage) {
      this.query.page = newPage
      this.getEmployeesList()
    }
  }
}
</script>

<style lang="scss" scoped></style>
